var env     = process.env.NODE_ENV || 'development';
var config  = require('../../config/config')[env];

var ucsrest = require('./ucsrest')();

var appId = '9a5e0acda6064188b260bfadf8e9f11e';
var friendlyName = '76598140';

var User    = require('../model/user').User;
var Group   = require('../model/group').Group;

//用户管理
exports.register = function (req, res) {

    var mobile,userId,nickname='';

    if (req.method == 'GET'){

        mobile = req.query.mobile;
        userId = mobile;
        nickname = req.query.nickname;
    }else if(req.method == 'POST'){

        mobile = req.body.mobile;
        userId = mobile;
        nickname = req.body.nickname;
    }

    var params = {"client":{
        "appId":appId,
        "friendlyName":friendlyName,
        "clientType":1,
        "charge":1,
        "mobile":mobile,
        "userId":mobile
    }};



    var ucs = new ucsrest();

    ucs.requestApi('POST', 'Clients', params, function (err, response, data) {

        var json_data = JSON.stringify(data);

        if (!err && response.statusCode == 200) {

            var resp = data['resp'];
            var code = resp.respCode;

            console.log('200 , success:'+resp);

            if (code == 0){

                var client = resp['client'];
                var _user = {
                    "imtoken":client['clientToken'],
                    "nickname":nickname,
                    "mobile":mobile,
                    "userId":userId,
                    "clientNumber":client['clientNumber'],
                    "clientPassword":client['clientPwd'],
                    "clientType":1,
                    "createDate":client['createDate'],
                    "groupList":[]};

                var user = new User(_user);

                user.save(function (err) {

                    if(err){
                        console.log('db err:'+err);
                        res.send({code:3,msg:"database error"});

                    }else{
                        console.log("db succ" + JSON.stringify(client));
                        res.send({code:0,user:_user});

                    }
                });

            }else{
                res.send({code:2,msg:code});
            }

        } else {
            console.log("http err : "+json_data);
            res.send({code:1,msg:response});
        }

    });

}

exports.login = function (req, res) {

    var mobile='',userId='';

    if (req.method == 'GET'){

        if (req.query.mobile){
            mobile = req.query.mobile;
        }


        if (req.query.userId) {
            userId = req.query.userId;
        }

    }else if(req.method == 'POST'){

        if (req.body.mobile){
            mobile = req.body.mobile;
        }

        if (req.body.userId){
            mobile = req.body.userId;
        }

    }

    var ucs = new ucsrest();

    var path,params;

    if (mobile != ''){
        path = 'ClientsByMobile';
        params = {
            "appId":appId,
            "mobile":mobile
        };
    }else if (userId != ''){
        path = 'ClientsByUserId';
        params = {
            "appId":appId,
            "userId":userId
        };
    }

    console.log('user login userid'+userId+',mobile='+mobile);

    ucs.requestApi('GET', path, params, function (err, response, data) {

        var json_data = JSON.stringify(data);

        if (!err && response.statusCode == 200) {

            var resp = data['resp'];
            var code = resp.respCode;

            if (code == 0){

                User.findOne({"mobile":mobile}, function (err, user) {
                    if (err){
                        console.log('db err:'+err);
                        res.send({code:3,msg:"find user err"});
                    }else{

                        if (user==null){
                            res.send({code:5,msg:'can`t find user,checku userId'});
                            return;
                        }
                        user._id = null;
                        res.send({code:0,user:user});

                    }

                });
            }else{
                //console.log("ok:" + JSON.stringify(data));
                res.send({code:2,msg:code});
            }


        } else {
            console.log("http err : "+response);
            res.send({code:1,msg:response});
        }
    });

}


//群组管理
exports.createGroup = function (req, res) {

    var groupName='',userId='';

    if (req.method == 'GET'){

        if (req.query.userId){
            groupName = req.query.groupName;
            userId = req.query.userId;
        }

    }else if(req.method == 'POST'){

        if (req.body.userId){
            groupName = req.body.groupName;
            userId = req.body.userId;
        }

    }

    User.findOne({"userId":userId}, function (err,user) {

        if(err){
            res.send({code:1,msg:'find user err'});
        }else{

            console.log('user='+user+', userId='+userId);

            if (user==null){
                res.send({code:5,msg:'can`t find user,checku userId'});
                return;
            }

            var groupId;
            var len = user.groupList.length;
            groupId = userId+(len+1).toString();

            var ucs = new ucsrest();
            var path = 'im/group/createGroup';
            var params = {
                "imGroup":{
                    "appId":appId,
                    "groupId":groupId,
                    "groupName":groupName,
                    "userId":userId
                }
            };

            ucs.requestApi('POST', path, params, function (err, response, data) {

                var json_data = JSON.stringify(data);

                if (!err && response.statusCode == 200) {
                    //console.log("ok:" + JSON.stringify(data));
                    var resp = data['resp'];
                    var code = resp['respCode'];

                    if (code == 0){

                        var memberCount = resp['memberCount'];
                        var memberList = [userId];
                        var _group = {
                            "groupId":groupId,
                            "groupName":groupName,
                            "createUserId":userId,
                            "memberCount":memberCount,
                            "memberList":memberList
                        };

                        var group = new Group(_group);

                        group.save(function (err) {

                            if(err){
                                res.send({code:3,msg:'save group err'});
                            }else{
                                User.findOne({"userId":userId}, function (err, user) {
                                    if(err){
                                        res.send({code:4,msg:"find user err : "});
                                    }else{

                                        if (user==null){
                                            res.send({code:5,msg:'can`t find user,checku userId'});
                                            return;
                                        }

                                        user.groupList.push(groupId);
                                        user.save(function (err) {
                                            if(err){
                                                res.send({code:5,msg:"save user err : "});
                                            }else{
                                                res.send({code:0,msg:user});
                                            }
                                        });

                                    }
                                });
                            }
                        });

                    }else{
                        res.send({code:2,msg:code});
                    }
                } else {
                    console.log("err : "+json_data);
                    res.send({code:1,msg:response});
                }
            });

        }

    });



}

exports.groupList  = function (req, res) {

    var userId;
    if (req.method == 'GET'){

        if (req.query.userId){
            userId = req.query.userId;
        }

    }else if(req.method == 'POST'){

        if (req.body.userId){
            userId = req.body.userId;
        }
    }
    console.log('find userId'+userId);

    User.findOne({"userId":userId}, function (err, user) {
        if (err){
            console.log('find user err:'+err);
            res.send({code:3,msg:'find user err'});

        }else{

            if (user==null){
                res.send({code:5,msg:'can`t find user,checku userId'});
                return;
            }

            user._id = null;

            var times = user.groupList.length;
            var tick = 0;

            var groups = [];
            if(user.groupList.length == 0){
                res.send({code:0,groups:groups});
            }else{
                user.groupList.forEach(function (groupId) {

                    console.log('times='+times+',tick='+tick+',gid='+groupId);

                    Group.findOne({"groupId":groupId}, function (err, group) {

                        if(err){
                            res.send({code:1,msg:'find group err'});
                        }else{
                            if(group){
                                group._id = null;
                                tick++;
                                if(tick==times){
                                    groups.push(group);
                                    res.send({code:0,groups:groups});
                                }else{
                                    groups.push(group);
                                }
                            }

                        }

                    });
                });
            }

        }
    });

}

exports.queryGroup = function (req, res) {

    var groupId='',groupName='',userId='';

    if (req.method == 'GET'){

        if (req.query.groupId){
            groupId = req.query.groupId;
            groupName = req.query.groupName;
            userId = req.query.userId;
        }

    }else if(req.method == 'POST'){

        if (req.body.groupId){
            groupId = req.body.groupId;
            groupName = req.body.groupName;
            userId = req.body.userId;
        }

    }

    var ucs = new ucsrest();

    var path = 'im/group/getGroup';
    var params = {
        "imGroup":{
            "appId":appId,
            "groupId":groupId,
            "groupName":groupName,
            "userId":userId
        }
    };

    ucs.requestApi('POST', path, params, function (err, response, data) {

        var json_data = JSON.stringify(data);

        if (!err && response.statusCode == 200) {
            //console.log("ok:" + JSON.stringify(data));
            res.send({code:0,msg:json_data});

        } else {
            console.log("err : "+json_data);
            res.send({code:1,msg:response});
        }
    });
}


exports.deleGroup = function (req, res) {

    var groupId='',groupName='',userId='';

    if (req.method == 'GET'){

        if (req.query.groupId){
            groupId = req.query.groupId;
            groupName = req.query.groupName;
            userId = req.query.userId;
        }

    }else if(req.method == 'POST'){

        if (req.body.groupId){
            groupId = req.body.groupId;
            groupName = req.body.groupName;
            userId = req.body.userId;
        }

    }

    var ucs = new ucsrest();

    var path = 'im/group/dismissGroup';
    var params = {
        "imGroup":{
            "appId":appId,
            "groupId":groupId,
            "groupName":groupName,
            "userId":userId
        }
    };

    ucs.requestApi('POST', path, params, function (err, response, data) {

        var json_data = JSON.stringify(data);

        if (!err && response.statusCode == 200) {

            Group.findOneAndRemove({"groupId":groupId}, function (err) {

                if(err){
                    res.send({code:1,msg:'find group err'});
                }else{

                    User.findOne({"userId":userId}, function (err, user) {
                        if(err){
                            res.send({code:1,msg:'find user err'});
                        }else{

                            if (user==null){
                                res.send({code:5,msg:'can`t find user,checku userId'});
                                return;
                            }

                            var groupList = user.groupList;
                            var pos = groupList.indexOf(groupId);
                            groupList.splice(pos, 1);

                            user.groupList = groupList;
                            user.save(function (err) {
                                if(err){
                                    res.send({code:1,msg:'save user err'});
                                }else{
                                    res.send({code:0,user:user});
                                }
                            });

                        }
                    });

                }

            });

            //res.send({code:0,msg:json_data});

        } else {
            console.log("err : "+json_data);
            res.send({code:1,msg:response});
        }
    });
}

exports.joinGroup = function (req, res) {

    var groupId='',groupName='',userId='';

    if (req.method == 'GET'){

        if (req.query.groupId){
            groupId = req.query.groupId;
            groupName = req.query.groupName;
            userId = req.query.userId;
        }

    }else if(req.method == 'POST'){

        if (req.body.groupId){
            groupId = req.body.groupId;
            groupName = req.body.groupName;
            userId = req.body.userId;
        }

    }

    var ucs = new ucsrest();

    var path = 'im/group/joinGroup';
    var params = {
        "imGroup":{
            "appId":appId,
            "groupId":groupId,
            "groupName":groupName,
            "userId":userId
        }
    };

    ucs.requestApi('POST', path, params, function (err, response, data) {

        var json_data = JSON.stringify(data);

        if (!err && response.statusCode == 200) {

            Group.findOne({"groupId":groupId}, function (err,group) {
                if(err){
                    res.send({code:1,msg:'find group err'});
                }else{

                    if(group){
                        var memberList = group.memberList;
                        memberList.push(userId);
                        group.memberList = memberList;

                        group.memberCount = group.memberCount + 1;

                        group.save(function (err) {
                            if(err){
                                res.send({code:1,msg:'save group err'});
                            }else{
                                User.findOne({"userId":userId}, function (err, user) {

                                    if(err){
                                        res.send({code:1,msg:'find user err'});
                                    }else{
                                        user.groupList.push(groupId);

                                        user.save(function (err) {
                                            if(err){
                                                res.send({code:1,msg:'save user err'});
                                            }else{
                                                group._id = null;
                                                res.send({code:0,user:user,group:group});
                                            }
                                        });
                                    }

                                });
                            }

                        });
                    }else{
                        res.send({code:3,msg:'can`t find group,check groupId'});
                    }

                }
            });
            //res.send({code:0,msg:json_data});

        } else {
            console.log("err : "+json_data);
            res.send({code:1,msg:response});
        }
    });
}

exports.updateGroup = function (req, res) {
    var groupId='',groupName='',userId='';

    if (req.method == 'GET'){

        if (req.query.groupId){
            groupId = req.query.groupId;
            groupName = req.query.groupName;
            userId = req.query.userId;
        }

    }else if(req.method == 'POST'){

        if (req.body.groupId){
            groupId = req.body.groupId;
            groupName = req.body.groupName;
            userId = req.body.userId;
        }

    }



    var ucs = new ucsrest();

    var path = 'im/group/updateGroup';
    var params = {
        "imGroup":{
            "appId":appId,
            "groupId":groupId,
            "groupName":groupName,
            "userId":userId
        }
    };

    ucs.requestApi('POST', path, params, function (err, response, data) {

        var json_data = JSON.stringify(data);

        if (!err && response.statusCode == 200) {
            //console.log("ok:" + JSON.stringify(data));
            Group.findOne({"groupId":groupId}, function (err, group) {
                if(err){
                    res.send({code:1,msg:'find group err'});
                }else{

                    if(group){
                        group.groupName = groupName;
                        group.save(function (err) {
                            if(err){
                                res.send({code:1,msg:'save group err'});
                            }else{
                                group._id = null;
                                res.send({code:0,group:group});
                            }
                        });
                    }else{
                        res.send({code:1,msg:'group is null'});
                    }

                }
            });
        } else {
            console.log("err : "+json_data);
            res.send({code:1,msg:response});
        }
    });
}

exports.quitGroup = function (req, res) {

    var groupId='',groupName='',userId='';

    if (req.method == 'GET'){

        if (req.query.groupId){
            groupId = req.query.groupId;
            groupName = req.query.groupName;
            userId = req.query.userId;
        }

    }else if(req.method == 'POST'){

        if (req.body.groupId){
            groupId = req.body.groupId;
            groupName = req.body.groupName;
            userId = req.body.userId;
        }

    }

    var ucs = new ucsrest();

    var path = 'im/group/quitGroup';
    var params = {
        "imGroup":{
            "appId":appId,
            "groupId":groupId,
            "groupName":groupName,
            "userId":userId
        }
    };

    ucs.requestApi('POST', path, params, function (err, response, data) {

        var json_data = JSON.stringify(data);

        if (!err && response.statusCode == 200) {
            //console.log("ok:" + JSON.stringify(data));
            Group.findOne({"groupId":groupId}, function (err, group) {
                if(err){
                    res.send({code:1,msg:'find group err'});
                }else{

                    if (group==null){
                        res.send({code:5,msg:'can`t find group,checku groupId'});
                        return;
                    }

                    var pos = group.memberList.indexOf(userId);
                    group.memberList.splice(pos, 1);

                    group.memberCount = group.memberCount - 1;

                    group.save(function (err) {
                        if(err){
                            res.send({code:1,msg:'save group err'});
                        }else{
                            User.findOne({"userId":userId}, function (err, user) {
                                if(err){
                                    res.send({code:1,msg:'find user err'});
                                }else{
                                    var pos = user.groupList.indexOf(groupId);
                                    user.groupList.splice(pos, 1);

                                    user.save(function (err) {
                                        if(err){
                                            res.send({code:1,msg:'save user err'});
                                        }else{
                                            group._id = null;
                                            res.send({code:0,user:user, group:group});
                                        }
                                    });
                                }
                            });
                        }
                    });

                }
            });
        } else {
            console.log("err : "+json_data);
            res.send({code:1,msg:response});
        }
    });

}